const ADSdk = require("ADSdk");
var PlayInfo = require("PlayInfo");
var FileServe = require("FileServe");
cc.Class({
    extends: cc.Component,

    properties: {
        backBtn: cc.Node,
        payTypeNode: cc.Node,
        selectedNumNode: cc.Node,
        cashOutBtn: cc.Node,
        bindBtn: cc.Node,
        noneyLabel: cc.Label,

        headIcon: cc.Sprite,
        nameLabel: cc.Label,
    },

    // TODO 头像
    showHeadUI() {
        let name = cc.sys.localStorage.getItem('NickName');
        if (name && name != "NaN") {

            this.hadBind = true;
            this.bindBtn.active = false;
        } else {
            this.hadBind = false;
            this.bindBtn.active = true;
            name = "游客"
        }
        this.nameLabel.string = name;
        let url = cc.sys.localStorage.getItem('HeadIconUrl');
        if (url && url != "NaN") {
            cc.loader.load({ url: url, type: "png" }, (err, texture) => {
                this.headIcon.spriteFrame = new cc.SpriteFrame(texture);
            });
        }

        this.isNewUser();
    },

    Show() {
        // TODO 广告 插屏
        ADSdk.showInsertAd(6);
        this.node.active = true;
    },

    Close() {
        ADSdk.hideInsertAd();
        this.node.active = false;
    },

    onLoad() {
        EventManager.on("GetUserInfo", this.getInfo.bind(this), this);
        this.backBtn.on("click", this._back, this);
        this.payTypeNode.children[0].on("click", this._payType, this);
        this.payTypeNode.children[1].on("click", this._payType, this);
        this.cashOutBtn.on("click", this._cashOut, this);
        this.bindBtn.on("click", this._bind, this);
        for (let i = 0; i < this.selectedNumNode.childrenCount; i++) {
            this.selectedNumNode.children[i].on("click", this._selectNum, this);
        }

        
        this.showUI();
        this.showHeadUI();

        this._PlayInfo = new PlayInfo();
        cc.log(this._PlayInfo)

    },

    showUI() {
        this.moneyNum = Utils.getRedPacketNum().toFixed(2);
        this.noneyLabel.string = "￥" + this.moneyNum;

        for (let i = 0; i < this.payTypeNode.childrenCount; i++) {
            let node = this.payTypeNode.children[i];
            let selectedIcon = node.children[0];
            if (i == 0) {
                selectedIcon.active = true;
            } else {
                selectedIcon.active = false;
            }
        }

        for (let i = 0; i < this.selectedNumNode.childrenCount; i++) {
            let node = this.selectedNumNode.children[i];
            let selectedIcon = node.children[0];
            if (i == 0) {
                node.active = false;
                selectedIcon.active = false;
            } else if (i == 1) {
                selectedIcon.active = true;
            } else {
                selectedIcon.active = false;
            }
        }

    },

    isNewUser(){
        console.log("=================判断是否是新用户")
        let openid = cc.sys.localStorage.getItem("OpenId");
        // TODO 新用户
        let url = "https://www.xiazero18.com/xl-xxl-api/api/thirdLogin?authid=" + openid + "&devicenum=aaa";
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                console.log(response);
                response = JSON.parse(response);

                cc.sys.localStorage.setItem("Token",response.data.token);
                if (response.data.isfreshuser) {
                    console.log("=================新用户")
                    this.selectedNumNode.children[0].active = true;
                    let event = { name: "btn_100<Button>" };
                    this._selectNum(event);
                }else{
                    console.log("=================老用户")
                    this.selectedNumNode.children[0].active = false;
                    let event = { name: "btn_200<Button>" };
                    this._selectNum(event);
                }
            } else {
                console.log("XMLHttpRequest 失败")
                console.log(xhr.readyState);
                console.log(xhr.status);
            }
        };
        xhr.open("POST", url, true);
        xhr.send();
    },

    _back(event) {
        // this.node.removeFromParent();
        this.Close();
    },

    _payType(event) {

        let id;
        let name = event.name;
        if (name == "btn_wechat<Button>") {
            id = 0;
        } else if (name == "btn_alipay<Button>") {
            id = 1;
        }

        for (let i = 0; i < this.payTypeNode.childrenCount; i++) {
            let node = this.payTypeNode.children[i];
            let selectedIcon = node.children[0];

            if (i == id) {
                selectedIcon.active = true;
            } else {
                selectedIcon.active = false;
            }
        }


    },

    _selectNum(event) {

        this.selectMoneyId;
        let name = event.name;
        switch (name) {
            case "btn_100<Button>":
                this.selectMoneyId = 0;
                break;
            case "btn_200<Button>":
                this.selectMoneyId = 1;
                break;
            case "btn_500<Button>":
                this.selectMoneyId = 2;
                break;
            case "btn_1000<Button>":
                this.selectMoneyId = 3;
                break;
        }

        for (let i = 0; i < this.selectedNumNode.childrenCount; i++) {
            // this.selectedNumNode.children[i].on("click", this._selectNum, this);
            let node = this.selectedNumNode.children[i];
            let selectedIcon = node.children[0];

            if (i == this.selectMoneyId) {
                selectedIcon.active = true;
            } else {
                selectedIcon.active = false;
            }
        }
    },


    _cashOut() {

        let level = 1;
        var cache = FileServe.Instance.GetPlayInfo();
        if(cache != null)
        {
            level = cache._Level;
        }

        cc.log("当前关卡：" + level)
        if (level < 10) {
            ADSdk.showToast("关卡10以后可提现");
            return;
        }

        cc.log("=================_cashOut")
        cc.log("=================selectMoneyId:" + this.selectMoneyId)
        switch (this.selectMoneyId) {
            case 0:
                let moneyNum = Utils.getRedPacketNum();
                if (moneyNum < 0.31) {
                    ADSdk.showToast("可提现金额不足");
                } else {
                    this.tixian();
                }
                break;
            case 1:
            case 2:
            case 3:
                let max = Utils.getMaxCash();
                let str = this.moneyNum < max ? "可提现金额不足" : "数据异常";
                ADSdk.showToast(str);
                break;
            default:
                cc.log("=================default")
                ADSdk.showToast("可提现金额不足");
                break;
        }
    },

    _bind() {
        
        ADSdk.login((result, data) => {
            // this.spriteFrameIcon = this.setQRCode(data);
            // this.showHeadUI()
        });
    },

    setQRCode(strQR){
        let strImg = "data:image/jpeg;base64," + strQR;
        let img = new Image();
        img.src = strImg
        let texture = new cc.Texture2D();
        texture.initWithElement(img);
        texture.handleLoadedTexture();

        return new cc.SpriteFrame(texture);
        // this.aSprite.spriteFrame = new cc.SpriteFrame(texture);
    },


    getInfo(data) {
        cc.log("=================获取用户信息")
        data = JSON.parse(data);
        let url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + data.accessToken + "&openid=" + data.openId;
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                console.log(response);
                response = JSON.parse(response);
                cc.sys.localStorage.setItem('NickName', response.nickname);
                cc.sys.localStorage.setItem('HeadIconUrl', response.headimgurl);

                ADSdk.showToast("登录成功");
                this.bindBtn.active = false;
                this.showHeadUI();
                EventManager.emit("showHeadUI");
            } else {
                console.log("XMLHttpRequest 失败")
                console.log(xhr.readyState);
                console.log(xhr.status);
            }
        };
        xhr.open("GET", url, true);
        xhr.send();
    },


    tixian() {
        // TODO 提现逻辑
        if (!this.hadBind) {
            ADSdk.showToast("请先绑定帐号");
            return;
        }
        let token = cc.sys.localStorage.getItem("Token");
        if (token && token != "NaN") {

        } else {
            ADSdk.showToast("网络异常，请关闭重试！");
            return;
        }
        console.log("===============tixian")
        console.log("===============token：" + token)
        let url = "https://www.xiazero18.com/xl-xxl-api/api/wxPay?amount=31";
        let xhr = new XMLHttpRequest();
        xhr.setRequestHeader('token', token);
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                console.log(response);
                response = JSON.parse(response);
                ADSdk.showToast(response.msg);

                this.selectedNumNode.children[0].active = false;
                let event = { name: "btn_200<Button>" };
                this._selectNum(event);
                
            } else {
                console.log("XMLHttpRequest 失败")
                console.log(xhr.readyState);
                console.log(xhr.status);
            }
        };
        xhr.open("POST", url, true);
        xhr.send();
    }


});
